<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('股东信息') }}</span>
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="addShareholder">{{ $t("新增股东") }}</el-button>
    </div>
    <el-empty v-show="validateForm.forms.length === 0 " description="暂无股东信息" />
    <el-form ref="form" v-loading="loading" :model="validateForm" label-width="120px" class="dataForm">
      <div v-for="(form, index) in validateForm.forms" :key="index" class="form-flex">
        <div class="area-header">
          <span class="area-header-title">股东{{ index + 1 }}</span>
          <span>
            <el-button size="mini" @click="savaOrUpdate(form,index)">{{ form.isEdit? $t("保存"):$t("编辑") }}</el-button>
            <el-button size="mini" @click="delShareholder(index)">{{ $t("删除") }}</el-button>
          </span>
        </div>
        <div class="flex">
          <el-form-item :label="$t('出资人类别')" :prop="'forms.' + index + '.investorCategory'" :rules="rules.investorCategory">
            <div v-if="form.isEdit === false" class="field">{{ form.investorCategory }}</div>
            <el-select v-else v-model="form.investorCategory" size="mini" placeholder="出资人类别">
              <el-option v-for="dict in investorCategoryOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('出资人')" :prop="'forms.' + index + '.investor'" :rules="rules.investor">
            <div v-if="form.isEdit === false" class="field">{{ form.investor }}</div>
            <template v-else>
              <el-input v-if="form.investorCategory=='waif'" v-model="form.investor" size="mini" placeholder="出资人" @blur="tycCompanyName(form)" />
              <el-select v-else v-model="form.investor" size="mini" placeholder="出资人" @change="getCreditCode(form.investor,index)">
                <el-option v-for="dict in internalOrgFundOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
              </el-select>
            </template>

          </el-form-item>
          <el-form-item :label="$t('社会信用代码')" :prop="'forms.' + index + '.creditCode'" :rules="rules.creditCode">
            <div v-if="form.isEdit === false" class="field">{{ form.creditCode }}</div>
            <el-input v-else v-model="form.creditCode" size="mini" placeholder="社会信用代码" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('所有制')" :prop="'forms.' + index + '.propertySystem'" :rules="rules.propertySystem">
            <div v-if="form.isEdit === false" class="field">{{ form.propertySystem }}</div>
            <el-select v-else v-model="form.propertySystem" size="mini" placeholder="所有制">
              <el-option v-for="dict in assetOwnershipOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('股权取得方式')" :prop="'forms.' + index + '.equityAcquisitionMethods'" :rules="rules.equityAcquisitionMethods">
            <div v-if="form.isEdit === false" class="field">{{ form.equityAcquisitionMethods }}</div>
            <el-select v-else v-model="form.equityAcquisitionMethods" size="mini" placeholder="股权取得方式">
              <el-option v-for="dict in dsEquityAcquisitionMethodOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('股权比例')" :prop="'forms.' + index + '.equityRatio'" :rules="rules.equityRatio">
            <div v-if="form.isEdit === false" class="field">{{ form.equityRatio }}</div>
            <Money v-else v-model="form.equityRatio" size="mini" placeholder="股权比例" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('持股分类')" :prop="'forms.' + index + '.equityHoldingTypes'" :rules="rules.equityHoldingTypes">
            <div v-if="form.isEdit === false" class="field">{{ form.equityHoldingTypes }}</div>
            <el-select v-else v-model="form.equityHoldingTypes" size="mini" placeholder="持股分类">
              <el-option v-for="dict in dsShareholdingTypeOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('长期股权成本(万元)')" :prop="'forms.' + index + '.longTermEquityCost'" :rules="rules.longTermEquityCost">
            <div v-if="form.isEdit === false" class="field">{{ form.longTermEquityCost }}</div>
            <Money v-else v-model="form.longTermEquityCost" size="mini" placeholder="长期股权成本" />
          </el-form-item>
          <el-form-item :label="$t('取得时间')" :prop="'forms.' + index + '.acquisitionTime'" :rules="rules.acquisitionTime">
            <div v-if="form.isEdit === false" class="field">{{ parseTime(form.acquisitionTime) }}</div>
            <DatePicker v-else v-model="form.acquisitionTime" size="mini" placeholder="取得时间" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('币种')" :prop="'forms.' + index + '.currencyType'" :rules="rules.currencyType">
            <div v-if="form.isEdit === false" class="field">{{ form.currencyType }}</div>
            <el-select v-else v-model="form.currencyType" size="mini" placeholder="币种">
              <el-option v-for="dict in currencyOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('认缴资本(万元)')" :prop="'forms.' + index + '.subscribedCapital'" :rules="rules.subscribedCapital">
            <div v-if="form.isEdit === false" class="field">{{ moneyFormat(form.subscribedCapital / 10000) }}</div>
            <Money v-else v-model="form.subscribedCapital" size="mini" placeholder="认缴资本" unit="w" />
          </el-form-item>
          <el-form-item :label="$t('实缴资本(万元)')" :prop="'forms.' + index + '.actualPaidCapital'" :rules="rules.actualPaidCapital">
            <div v-if="form.isEdit === false" class="field">{{ moneyFormat(form.actualPaidCapital / 10000) }}</div>
            <Money v-else v-model="form.actualPaidCapital" size="mini" placeholder="实缴资本" unit="w" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('出资方式')" :prop="'forms.' + index + '.investmentMethod'" :rules="rules.investmentMethod">
            <div v-if="form.isEdit === false" class="field">{{ form.investmentMethod }}</div>
            <el-select v-else v-model="form.investmentMethod" size="mini" placeholder="出资方式">
              <el-option v-for="dict in dsFundingMethodOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('所在地区')" :prop="'forms.' + index + '.region'" :rules="rules.region">
            <div v-if="form.isEdit === false" class="field">{{ form.region }}</div>
            <el-input v-else v-model="form.region" size="mini" placeholder="所在地区" />
          </el-form-item>
          <el-form-item label="" prop="" />
        </div>
        <div class="flex">
          <el-form-item :label="$t('备注')" prop="remark">
            <div v-if="form.isEdit === false" class="field">{{ form.remark }}</div>
            <el-input v-else v-model="form.remark" type="textarea" :rows="2" size="mini" placeholder="备注" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('董事会席位数量')" prop="boardSeatsCount">
            <div class="field">{{ form.boardSeatsCount }}</div>
          </el-form-item>
          <el-form-item :label="$t('职位类型')" prop="boardSeatsList">
            <el-checkbox-group v-if="!form.isEdit" v-model="form.boardSeatsList">
              <el-checkbox v-for="(option, index) in positionTypeOptions" :key="index" :label="option.dictValue" disabled>{{ option.dictLabel }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('监事会席位数量')" :prop="'forms.' + index + '.supervisoryBoardSeatCount'" :rules="rules.supervisoryBoardSeatCount">
            <div v-if="form.isEdit === false" class="field">{{ form.supervisoryBoardSeatCount }}</div>
            <el-input-number v-else v-model="form.supervisoryBoardSeatCount" controls-position="right" :min="1" :max="10" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('职位类型')" :prop="'forms.' + index + '.supervisorPositionTypeList'" :rules="rules.supervisorPositionTypeList">
            <el-checkbox-group v-if="!form.isEdit" v-model="form.supervisorPositionTypeList">
              <el-checkbox v-for="(option, index) in positionTypeOptions2" :key="index" :label="option.dictValue" disabled>{{ option.dictLabel }}</el-checkbox>
            </el-checkbox-group>
            <el-checkbox-group v-else v-model="form.supervisorPositionTypeList">
              <el-checkbox v-for="(option, index) in positionTypeOptions2" :key="index" :label="option.dictValue">{{ option.dictLabel }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </div>
    </el-form>

  </div>
</template>

<script>
import {
  delDsShareHolder,
  saveDsShareHolder,
  findListByCompanyId,
  getDsShareHolder,
  queryInternalOrgFund
} from '@/api/fund/ds/dsShareHolder'
import { companyDetailsByName } from '@/api/company/base/companyBase'

export default {
  components: {},
  data() {
    return {
      loading: false,
      companyId: this.$route.query.companyId,
      validateForm: {
        forms: []
      },
      rules: {
        investorCategory: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        investor: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        creditCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        propertySystem: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        equityAcquisitionMethods: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        equityRatio: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        equityHoldingTypes: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        longTermEquityCost: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        acquisitionTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        currencyType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        subscribedCapital: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        actualPaidCapital: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        investmentMethod: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        region: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        supervisoryBoardSeatCount: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        supervisorPositionTypeList: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      internalOrgFundOption: [],
      positiontypeOptions: [],
      positiontypeOptions2: [],
      investorCategoryOption: [],
      assetOwnershipOption: [],
      dsEquityAcquisitionMethodOption: [],
      currencyOption: [],
      dsShareholdingTypeOption: [],
      dsFundingMethodOption: []
    }
  },
  // watch: {
  //   validateForm: {
  //   handler: function() {
  //     this.$nextTick(() => {
  //       console.log('123')
  //         window.scrollTo({
  //           top: this.$el.scrollHeight,
  //           behavior: 'smooth'
  //         })
  //       })
  //   },
  //   deep: true
  // }
  // },
  created() {
      this.initDict()
      this.getList()
      queryInternalOrgFund().then(res => {
          this.internalOrgFundOption = res.data
      })
  },
  methods: {
    initDict() {
      this.getDicts('ds_zw').then(response => {
        this.positionTypeOptions = response.data
      })
      this.getDicts('ds_position_type2').then(response => {
        this.positionTypeOptions2 = response.data
      })
      this.getDicts('ds_investor_category').then(response => {
        this.investorCategoryOption = response.data
      })
      this.getDicts('ds_asset_ownership').then(response => {
        this.assetOwnershipOption = response.data
      })
      this.getDicts('ds_equity_acquisition_method').then(response => {
        this.dsEquityAcquisitionMethodOption = response.data
      })
      this.getDicts('currency').then(response => {
        this.currencyOption = response.data
      })
      this.getDicts('ds_shareholding_type').then(response => {
        this.dsShareholdingTypeOption = response.data
      })
      this.getDicts('ds_funding_method').then(response => {
        this.dsFundingMethodOption = response.data
      })
    },
    delShareholder(index) {
      const row = this.validateForm.forms[index]
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
          .then(() => {
            delDsShareHolder(id)
            this.validateForm.forms.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
      } else {
        this.validateForm.forms.splice(index, 1)
      }
    },
    addShareholder() {
      const addHolderObj = {
        isEdit: true,
        companyId: this.companyId,
        investorCategory: undefined,
        investor: undefined,
        creditCode: undefined,
        propertySystem: undefined,
        equityAcquisitionMethods: undefined,
        equityRatio: undefined,
        equityHoldingTypes: undefined,
        longTermEquityCost: undefined,
        acquisitionTime: undefined,
        currencyType: undefined,
        subscribedCapital: undefined,
        actualPaidCapital: undefined,
        investmentMethod: undefined,
        region: undefined,
        supervisoryBoardSeatCount: undefined,
        supervisorPositionType: undefined,
        boardSeatsList: [],
        supervisorPositionTypeList: []
      }
      this.validateForm.forms.push(addHolderObj)
    },
    savaOrUpdate(form, index) {
      const row = this.validateForm.forms[index]
      const editFlag = !form.isEdit
      if (editFlag) {
        if (row.id) {
          getDsShareHolder(row.id).then(response => {
            if (response.code === 200) {
              const keys = Object.keys(response.data)
              for (const key of keys) {
                this.$set(this.validateForm.forms[index], key, response.data[key])
              }
              this.$set(this.validateForm.forms[index], 'isEdit', editFlag)
              this.$forceUpdate()
            }
          })
        }
        this.$forceUpdate()
        return
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
        this.validateForm.forms[index].isEdit = editFlag
          this.loading = true
          row.supervisorPositionType = row.supervisorPositionTypeList ? row.supervisorPositionTypeList.toString() : ''
          saveDsShareHolder(row).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.getList()
            } else {
              this.msgError(response.msg)
            }
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    getList() {
      this.loading = true
      const queryParam = { companyId: this.companyId }
      findListByCompanyId(queryParam).then(response => {
        this.validateForm.forms = response.data
        this.validateForm.forms.map(item => {
          item.isEdit = false
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    tycCompanyName(form) {
       const queryParam = {
          companyName: form.investor,
          orgType: '1'
       }
      companyDetailsByName(queryParam).then(res => {
        if (res.msg === 'exist') {
          form.creditCode = res.data.creditCode
        } else if (res.msg === 'nofind') {
          form.creditCode = ''
          this.msgError(this.$t('天眼查没有获取到该公司信息！'))
        } else {
          form.creditCode = res.data.creditCode
          }
        })
      },
      getCreditCode(val, index) {
        console.log('val', val)
        const matchingOption = this.internalOrgFundOption.find(option => option.dictValue === val)
        if (matchingOption) {
          console.log('matchingOption', matchingOption)
          this.validateForm.forms[index]['creditCode'] = matchingOption.creditCode
        }
      }
  }
}
</script>

<style lang="scss" scoped>
.area-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form-flex {
  background: #F7F9FE;
  box-shadow: 0 0 3px 1px #ebeef3;
  margin-bottom: 15px;
  border-radius: 5px;

  .area-header {
    margin: 0;
    padding: 5px 10px;
    border-bottom: 1px solid #ebeef3;

    .area-header-title::before {
      width: 6px;
      height: 6px;
      border-radius: 50%;
    }
  }

  /deep/.flex {
    display: flex;
    border-bottom: 1px solid #ebeef3;

    .el-form-item {
      flex: 1;
      margin: 0;
      border-right: 1px solid #ebeef3;

      .el-form-item__label {
        width: 145px !important;
        max-width: 145px !important;
        text-align: left;
        padding: 5px 10px;
        border-right: 1px solid #ebeef3;
        color: #303133;
        font-weight: 400;
        line-height: normal;
        display: flex;
        align-items: center;
        height: 100%;
        white-space: normal;
      }

      .field {
        height: 100%;
        display: flex;
        align-items: center;
      }

      .el-form-item__content {
        padding: 5px 10px;
        background: #fff;
        line-height: normal;
        height: 100%;
        margin-left: 140px !important;

        .el-select,
        .el-date-editor {
          width: 100%;
        }
      }
    }
  }
}
</style>
